<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\User as userModel;
use app\admin\model\AuthGroup as authGroupModel;
use app\admin\model\CapitalFlow as capitalFlowModel;
use app\admin\validate\User as userValidate;
use think\exception\ValidateException;
use EasyWeChat\Factory;
use think\facade\Db;
use think\facade\View;

class User extends Base{
    // 添加编辑
    public function edit($id=0){
	    // 判断用户组是否存在
	    $authGroupRs = Db::name('auth_group')->where('signid',1)->select();
	    if(empty($authGroupRs)) return json(lang('c_add_first').lang('v_authgroup'));
		
	    if(!request()->isPost()){
            $rs = Db::name('user')->where('id',$id)->find();
            
		    // 所属用户组
            View::assign('authGroup',$authGroupRs);
		    // 用户-用户组
            View::assign('authGroupAccess',Db::name('auth_group_access')->where('uid',$id)->find());
            View::assign('rs',userModel::find($id));

            // 会员组
		    View::assign('grouplist',Db::name('auth_group')->select());

            // 地区
            $areaArr = json_encode(getAreaArr('Area',0,$this->lang));
            View::assign('areaArr',$areaArr);
        
            // 编辑信息时获取地区ID
            $a = ""; $b = ""; $c = ""; $d = "";
            $areaRs =  getParentSort(Db::name('area')->select(),$rs['areaid']);
            foreach($areaRs as $k => $v){
                $abcd = $v['id'];
                switch($k){
                    case 0:
                        $a = $abcd;
                        break;
                    case 1:
                        $b = $abcd;
                        break;
                    case 2:
                        $c = $abcd;
                        break;
                    case 3:
                        $d = $abcd;
                        break;
                }
            }
            View::assign('a',$a); View::assign('b',$b); View::assign('c',$c); View::assign('d',$d);
			
            return view();
		}else{
            // 表单验证
            try {
                if($id > 0){//编辑
                    validate(userValidate::class)->scene('edit')->check(input('post.'));
                }else{
                    validate(userValidate::class)->check(input('post.'));
                }
            } catch (ValidateException $e) {
                return json(['code' => 1001, 'msg' => $e->getMessage(), 'data' => '']);
            }

            try {
                userModel::edit($id);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
		}
    }

    // 列表
    public function index($keyword=""){
    	$signid = input('signid'); $group_id = input('group_id');

    	$keyword = input('keyword'); $order = ['user.sequence'=>'desc','user.id'=>'desc'];
    	if(empty($signid)) $signid = 1;

        // 模板
        $template = ''; $method = input('method'); $listNum = 20;
        if(request()->isAjax()){
            switch ($method) {
                case 'signle':
                    $template = 'signle_check';
                    break;
                default:
                    $template = 'checklist';
                    $listNum = 10;
                    break;
            }
        }

		$rs = userModel::index($this->lang,$group_id,$signid,$listNum,$keyword,$order);

		//1正常9已删除，大于9就是删除时间戳
        View::assign('signid',$signid);

		//会员组
		View::assign('grouplist',Db::name('auth_group')->select());

		View::assign('list',$rs);
		View::assign('total',$rs->total());
		View::assign('lastPage',$rs->lastPage());

		//编辑优惠券状态下，获取已选中的会员
		$couponid = input('couponid'); $user_json = array(); $user_json_str = '';
		if(!empty($couponid)){
			$couponRs = Db::name('shop_coupon')->where('id','>',0)->find($couponid);
			if(!empty($couponRs)){
				if(!empty($couponRs['user_json']) and $couponRs['user_json'] != 0){
					$user_json = explode(',', $couponRs['user_json']);
					$user_json_str = $couponRs['user_json'];
				}
			}
		}
		View::assign('user_json',$user_json);
		View::assign('user_json_str',$user_json_str);

        return view($template);
    }

    // 单个更新会员表的signid标记：1正常9软删除
    public function update_signid(){
        $id = input('id'); $signid = input('signid');
        // 参数不能为空
        if(empty($id) or empty($signid)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('id'=>$id)]);
        }
        // 软删除
        if($signid == 9) $signid = time();
        
        try {
            Db::name('user')->where('id',$id)->update(['signid'=>$signid]);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    // 批量更新会员表的signid标记：1正常9软删除
    public function updateall_signid(){
        $selectid = input('selectid/a'); $signid = input('signid');
        // 参数错误
        if(empty($selectid) or empty($signid)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }
        // 软删除
        if($signid == 9) $signid = time();
        
        try {
            Db::name('user')->where('id','in',$selectid)->update(['signid'=>$signid]);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('selectid'=>$selectid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }
	
	// 单条删除
    public function delete_one(){
		$id = input('id');
	    if($id == 1){
            return json(['code' => 1001, 'msg' => lang('c_delete_cannot_admin'), 'data' => array('id'=>$id)]);
        }
		
		$user = userModel::find($id);
		if(config('app.other.deletefile') == 1){//删除对应的图片
		    $avatar = substr($user['avatar'],1);
            @unlink($avatar);
        }
        
        try {
            // 删除数据
            $user->delete($id);
            // 删除用户组的一一对应的关系
            Db::name('auth_group_access')->where('uid',$id)->delete($id);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	// 批量删除
    public function delete_all(){
		$selectid = input('selectid/a');
		if(empty($selectid)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }
		
		if(in_array("1",$selectid)){
            return json(['code' => 1002, 'msg' => lang('c_delete_cannot_admin'), 'data' => array('selectid'=>$selectid)]);
        }

        $deletefile = config('app.other.deletefile');
		foreach($selectid as $i => $rs){
		    $id = $selectid[$i];
			$user = userModel::find($id);
			if($deletefile == 1){//删除对应的图片
			    $avatar = substr($user['avatar'],1);
                @unlink($avatar);
            }
            $deleteid[] = $id;
	    }

        try {
            //执行删除
            Db::name('user')->delete($deleteid);
            //删除一一对应关系
            Db::name('auth_group_access')->where('uid','in',$deleteid)->delete();
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('deleteid'=>$deleteid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    // 账户余额，积分，可提现金额调整
    public function capital(){
        $userid = input('userid');
        $userRs = userModel::getUser($userid);
        View::assign('userRs',$userRs);

    	if(!request()->isPost()){
    		return view();
    	}else{
            $balance = $userRs['balance'] + input('balance'); $score = $userRs['score'] + input('score'); $cash = $userRs['cash'] + input('cash');
            
            try {
                capitalFlowModel::edit($balance,$score,$cash);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('userid'=>$userid)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
    	}
    }

    /*查看会员信息*/
    public function view(){
        $userid = input('userid');
        $userRs = userModel::getUser($userid);

        View::assign('userRs',$userRs);
        return view();
    }

    /*退出
    * 返回json值：error失败，success成功
    */
    public function logout(){
        session(null);
        cookie('bmkj_closetips', null);
        $this->redirect(url('/login/index'));
    }
}